// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

/*!
* Drumcomputer JavaScript Library v0.4
* http://saquery.com
*
* Copyright 2010, Stephan Ahlf 
*/ 
(function(){
	if (!window.saq) window.saq={};		
	var _drumComputer = { 
		toggleStartStop:function(sender){
			if ($(sender).attr('value')=="Play"){
				this.toggleButtonColor = $(sender).css('background-color');
				$(sender).css({'background-color':'red'});
				this.start(sender);
				$(sender).attr('value','Stop');
			}else{
				$(sender).css({'background-color':this.toggleButtonColor});
				this.stop(sender);
				$(sender).attr('value', 'Play');
			}
		},
		start:function(sender){			
			//$(sender).toggle(function(){
				//}, function () {
			//});
			this.timer.start();
		},
		stop:function(sender){
			$(sender).css({'background-color':'white'});
			this.timer.stop();
		},
		loadSample:function(ident,uri,position){
			//var _test = this._audio(uri);
			
		
			var _snd = $('<audio/>',{
				id:ident,
				name:ident,
				autostart:false,
				width:0,
				height:0,
				src: 'http://jdrums.googlecode.com/svn/trunk/'+uri+'.wav'
			});
			
			
			_snd.appendTo($('#drumcomputer'));		

			this.samples.push({
				id:ident,
				fn:uri,
				pos:position,
				sound:_snd[0],
				stop:function(){
					//$('#'+this.id).each(function(){				
					    try {
						    this.sound.pause();
						} catch (e) {
						debugger;
							saq.drumComputer.stop();
							alert(':O( --- Error.');
						} finally {
							
						}
					//});
				},
				play:function(){
					var _ = $('#BP_DC_'+this.pos+'_1');
					
					window.setTimeout(function(){
						_.css('backgroundColor','red');
						window.setTimeout(function(){_.css('backgroundColor','white')},200);
					},1);
					//$('#'+this.id).each(function(){				
					;
					    try {
						    this.sound.pause();
							this.sound.currentTime= 0.0;
						    this.sound.volume=0.5;
							this.sound.play();
						} catch (e) {
							saq.drumComputer.stop();
							alert(':O( --- Error.');
						} finally {
							
						}
					//});					
					
				}
			});
			var i =0;
		},
		play:function(samples){
			$(this.samples).each(function(){				
				this.play();
			});
		},
		setBpm:function(bpm){this.timer.bpm=bpm;},
		_audio:function(fn){
			var _result = document.createElement('audio');
			_result.setAttribute('src', fn);
			_result.load();
			return _result;
			/*
			_result.addEventListener("load", function() { 
				_result.play(); 
				$(".duration span").html(_result.duration);
				$(".filename span").html(_result.src);
			}, true);



				
				$('.play').click(function() {
					_result.play();
					
				});
				$('.pause').click(function() {
					_result.pause();
				});
				$('.volumeMax').click(function() {
					_result.volume=1;
				});
					$('.volumestop').click(function() {
					_result.volume=0;
				});
				$('.playatTime').click(function() {
					_result.currentTime= 35;
					_result.play();
				});						
			*/
		},
		_timer:function(bpm){
			this.bpm = bpm;
			this.steps = 32;
			this.step=0;
			this.onTick=function(timer){
				if (!this.stopped){
					this.tick();
					saq.drumComputer.timer.play();
					if (this.step<this.steps-1){this.step+=1;} else {
						this.step=0;
						//document.title='';
					};
					//saq.drumComputer.play($('#sample1, #sample2'));
				}
			},
			this.tick=function(){
				if (!this.stopped){
					var _timer = (4 /* minutes */ * 60 /* seconds */ * 1000 /* milliseconds*/ / this.bpm) / this.steps;
					window.setTimeout(function(){
						saq.drumComputer.timer.onTick();
					},_timer);	
					
				}
			},
			this.start=function() {
				this.stopped = false;
				this.step=0;
				this.tick();
			},
			this.stop=function(){
				this.stopped=true;
				this.step=0;
			},
			this.play=function(){
					for(var i=0; i<this.sequenz[this.step].samples.length; i++){
							if (this.sequenz[this.step].samples[i]) this.sequenz[this.step].samples[i].play();
					}
					//document.title=document.title+":"+this.step+"; ";
			},
			this.sequenz=new Array();
			for(var i=0; i<this.steps; i++){
					this.sequenz.push({
					samples:new Array(),play:function(){
					}});
			}
			var i =0;
		},
		isInteger:function(s) {
			return (s.toString().search(/^-?[0-9]+$/) == 0);
		},
		init:function(debugMode){
			this.samples = new Array();
			
			this.loadSample('Base','test',0);
			this.loadSample('Base+Hihat','test2',1);
			this.loadSample('Snare','snare',2);
			
			this.timer = new this._timer(100);

			
			this.timer.sequenz[0*4].samples[0]=(this.samples[0]);
			this.timer.sequenz[3*4].samples[0]=(this.samples[0]);
			this.timer.sequenz[2*4].samples[2]=(this.samples[2]);
			this.timer.sequenz[5*4].samples[0]=(this.samples[0]);
			this.timer.sequenz[6*4].samples[2]=(this.samples[2]);
			this.timer.sequenz[7*4].samples[1]=(this.samples[1]);
			
			
			var _table = $('<table/>',{
				id:'bp_dc',
				border:1
			});
			
			for(var r=0; r<this.samples.length; r++){
				var _tr = $('<tr/>',{
				});
				$('<td/>',{ 
					innerHTML:this.samples[r].id,
					css:{width:'200px',height:'10px'}
					
				}).click(function(){
					alert($(this).attr('innerHTML')+': So far you cannot change a sample.');}
				).appendTo(_tr);

				$('<td/>',{ 
					id:'BP_DC_'+r+'_1',
					innerHTML:'PLAY',
					css:{width:'50px',height:'10px'}
					
				}).click(function(){
					var _sampleId = $(this).parent().attr('rowIndex');
					saq.drumComputer.samples[_sampleId].play();
					//$(this).attr('cellIndex')
				}).appendTo(_tr);

				
				for(var c=0; c<this.timer.steps; c++){
					var _active = '';
					var _color = '#CCD9FF';
					var _sample = this.timer.sequenz[c].samples[r];
					if (_sample==undefined) _sample=null;
					if (c % (this.timer.steps/4) == 0) _color='#668CFF'; 
					else if (c % 4==0) _color = "#99B3FF";
					if (_sample){
						_active="X";
					}
					$('<td/>',{ 
						innerHTML:_active,
						css:{'background-color':_color,width:'20px',height:'10px','text-align':'center','cursor':'pointer'}
					}).click(function(){
						var _newValue = '';
						if ($(this).attr('innerHTML')=='') _newValue='X';
						
						
						if (_newValue=='X') {
							var _step = $(this).attr('cellIndex')-2;
							var _sampleId = $(this).parent().attr('rowIndex');
							var _s = saq.drumComputer.timer.sequenz;							
							_s[_step].samples[_sampleId]=saq.drumComputer.samples[_sampleId];
							if (_s[_step].samples[_sampleId]) $(this).attr('innerHTML',_newValue);
						}else{
							var _step = $(this).attr('cellIndex')-2;
							var _sampleId = $(this).parent().attr('rowIndex');
							var _s = saq.drumComputer.timer.sequenz;	
							if (_s[_step].samples[_sampleId]){
								_s[_step].samples[_sampleId].stop();	
								_s[_step].samples.remove(_sampleId);
								if (!_s[_step].samples[_sampleId]) $(this).attr('innerHTML',_newValue); 
							} else {
								$(this).attr('innerHTML',_newValue);
							}
						}
					}).appendTo(_tr);
				}
				_tr.appendTo(_table);
			}
			_table.appendTo($('#drumcomputer'));	
		}
	}
	if (!window.saq.drumComputer) window.saq.drumComputer=_drumComputer;		
})();
$(function(){saq.drumComputer.init(true);});

$(document).ready(function() {	
});
